package com.dongfg.zcmserver.utils;

import com.dongfg.zcmserver.config.Config;
import com.dongfg.zcmserver.config.Message;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;

/**
 * zookeeper client manage.
 * Created by 13071472 on 2015/11/2.
 */
public class ClientManager {

    private static final Logger LOGGER = LoggerFactory.getLogger(ClientManager.class);

    // Prevent OOM Set max size.
    private static Map<String, ZooKeeper> clientMap = new ConcurrentHashMap<>(10000);

    /**
     * getClient from cache.
     *
     * @param securityKey generateSecurityKey by DigestUtils#generateSecurityKey
     * @return ZooKeeper client
     * @see DigestUtils#generateSecurityKey(String)
     */
    public static ZooKeeper getClient(String username, String securityKey) {

        ZooKeeper zooKeeper = clientMap.get(securityKey);
        try {
            if (zooKeeper == null || !zooKeeper.getState().isAlive()) {
                CountDownLatch latch = new CountDownLatch(1);
                zooKeeper = new ZooKeeper(Config.connectString, Config.sessionTimeout, event -> {
                    if (event.getState() == Watcher.Event.KeeperState.SyncConnected) {
                        latch.countDown();
                    }
                    LOGGER.info(event.toString());
                });
                latch.await();
                zooKeeper.addAuthInfo(Config.DIGEST_SCHEME, (username+":"+securityKey).getBytes());
            }
            clientMap.put(securityKey, zooKeeper);
        } catch (IOException | InterruptedException e) {
            LOGGER.error(Message.connectFail, e);
        }

        return zooKeeper;
    }

}
